package com.zijie.hosptal.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zijie.hosptal.aop.Log;
import com.zijie.hosptal.common.Result;
import com.zijie.hosptal.pojo.dto.PatientAccountDTO;
import com.zijie.hosptal.pojo.po.Patient;
import com.zijie.hosptal.service.PatientService;
import com.zijie.hosptal.util.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/patient")
public class PatientController {
    private PatientService patientService;
    @Autowired
    public void setPatientService(PatientService patientService) {
        this.patientService = patientService;
    }
    //查询全部
    @Log
    @GetMapping
    public Result<?> getAllPatientList(Integer page, Integer limit, Patient patient) {
        if (page==null&&limit==null){
            List<Patient> list = patientService.getAllPatient();
            return Result.success(list);
        }else {
            Page<Patient> patientPage=Page.of(page,limit);
            patientPage = patientService.list(patientPage, patient);
            return Result.success(patientPage);
        }

    }
    //添加
    @PostMapping
    public Result<?> addPatient(@Validated @RequestBody Patient patient, BindingResult bindingResult){
        boolean flag = patientService.save(patient);
        if (bindingResult.hasErrors()){
            // 获取第一个错误信息
            String errorMessage = bindingResult.getFieldError().getDefaultMessage();
            return Result.fail(errorMessage);
        }
        return Result.success(flag);
    }
    //修改患者信息
    @PutMapping
    public Result<?> updatePatient(@Validated @RequestBody Patient patient,BindingResult bindingResult){
        boolean flag = patientService.updateById(patient);
        if (bindingResult.hasErrors()){
            // 获取第一个错误信息
            String errorMessage = bindingResult.getFieldError().getDefaultMessage();
            return Result.fail(errorMessage);
        }
        return Result.success(flag);
    }
    //验证某个用户的密码
    @PostMapping("/verifyPassword")
    public Result<?> verifyPassword(@RequestBody PatientAccountDTO patientAccountDTO){
        Patient patient = patientService.getById(patientAccountDTO.getId());
        if (patient==null){
            return Result.fail("用户不存在");
        }
        if(Md5Util.getMD5String(patientAccountDTO.getPassword()).equals(patient.getPassword())){
            return Result.success();
        }
        return Result.fail("密码错误");
    }


}
